package com.hankol.winecellar.utils

import android.text.Editable
import android.text.TextWatcher
import android.widget.EditText
import android.widget.TextView

object EditInputUtils {
    /**输入框输入限制字数
     * @author: merbng
     * @time: 2022/6/17 15:02
     * @description:
     */
    fun numEditText(et: EditText, tvNum: TextView, limit: Int) {
        et.addTextChangedListener(object : TextWatcher {
            //记录输入的字数
            var enterWords: CharSequence = ""
            //已经输入字符的个数
            var enteredWords: Int = 0
            var selectEnd: Int = 0
            var selectStart: Int = 0
            override fun afterTextChanged(s: Editable?) {

            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence, start: Int, before: Int, count: Int) {
                //实时记录输入的字数
                enterWords = s;
                enteredWords = limit - s.length;
                //TextView显示剩余个数
                tvNum.setText("${limit - enteredWords}/${limit}");
                selectStart = et.getSelectionStart();
                selectEnd = et.getSelectionEnd();
                //当字数大于500时
                if (enterWords.length > limit) {
                    //设置光标在最后
                    et.setSelection(selectEnd);
                }
            }
        })
    }
}